package com.tanhua.dubbo.api;

import com.tanhua.model.mongo.Video;
import com.tanhua.model.mongo.VideoLike;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.util.StringUtils;

@DubboService
public class LikeVideoApiImpl implements LikeVideoApi{

    @Autowired
    private MongoTemplate mongoTemplate;

    //查询是否点赞
    @Override
    public Boolean hasLike(Long userId, Long videoId) {
        Query query = Query.query(Criteria.where("userId").is(userId).and("videoId").is(videoId));
        VideoLike videoLike = mongoTemplate.findOne(query, VideoLike.class);
        if (StringUtils.isEmpty(videoLike)){
            return false;
        }
        return true;
    }

    //保存点赞数据
    @Override
    public void save(VideoLike videoLike) {

        //保存点赞数据
        mongoTemplate.save(videoLike);

        //更新点赞数量
        Video video = mongoTemplate.findById(videoLike.getVideoId(), Video.class);
        Integer likeCount = video.getLikeCount();
        video.setLikeCount(++likeCount);
        mongoTemplate.save(video);
    }
}
